<?php
namespace plugin\ky_shouyin\app\controller\admin;

use support\Request;
use support\Db;
use plugin\ky_shouyin\app\controller\BaseController;

class StaffController extends BaseController
{
    /**
     * 员工管理页面
     */
    public function index()
    {
        return $this->view('admin/staff/index');
    }

    /**
     * 获取员工列表
     */
    public function list(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 15);
        $keyword = $request->input('keyword', '');
        
        $query = Db::table('ky_staff')
            ->leftJoin('ky_store', 'ky_staff.store_id', '=', 'ky_store.id')
            ->select('ky_staff.*', 'ky_store.name as store_name');

        if ($keyword) {
            $query->where(function($query) use ($keyword) {
                $query->where('ky_staff.name', 'like', "%{$keyword}%")
                      ->orWhere('ky_staff.phone', 'like', "%{$keyword}%");
            });
        }

        $total = $query->count();
        $staff = $query->offset(($page - 1) * $limit)
                      ->limit($limit)
                      ->orderBy('ky_staff.id', 'desc')
                      ->get();

        return json([
            'code' => 0,
            'msg' => 'success',
            'count' => $total,
            'data' => $staff
        ]);
    }

    /**
     * 添加员工
     */
    public function add(Request $request)
    {
        if ($request->method() === 'POST') {
            $data = $request->post();
            
            try {
                // 验证手机号是否已存在
                $exists = Db::table('ky_staff')
                    ->where('username', $data['username'])
                    ->exists();
                    
                if ($exists) {
                    return json(['code' => 1, 'msg' => '该用户名已存在']);
                }

                
                // 创建员工
                $staffId = Db::table('ky_staff')->insertGetId([
                    'username' => $data['username'], // 添加登录账号
                    'name' => $data['name'],
                    'phone' => $data['phone'],
                    'password' => password_hash($data['password'], PASSWORD_DEFAULT), // 密码
                    'store_id' => $data['store_id'],
                    'role' => $data['role'],
                    'status' => $data['status'],
                    'created_at' => date('Y-m-d H:i:s')
                ]);
                
                // 添加管理员记录
                $adminId = Db::table('wa_admins')->insertGetId([
                    'username' => $data['username'], // 使用员工姓名作为用户名
                    'nickname' => $data['name'], // 显示名称
                    'password' => password_hash($data['password'], PASSWORD_DEFAULT), // 密码
                    'mobile' => $data['phone'], // 手机号码
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                    'status' => $data['status'] // 状态
                ]);
                
                // 更新员工表，记录 admin_id
                Db::table('ky_staff')->where('id', $staffId)->update(['admin_id' => $adminId]);
                
                // 添加角色记录到 wa_admin_roles 表
                Db::table('wa_admin_roles')->insert([
                    'admin_id' => $adminId,
                    'role_id' => $data['role'] // 使用前端传递的角色 ID
                ]);
                
                return json(['code' => 0, 'msg' => '添加成功']);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => '添加失败：' . $e->getMessage()]);
            }
        }
        
        // 获取门店列表
        $stores = Db::table('ky_store')->where('status', 1)->get();
        return $this->view('admin/staff/add', ['stores' => $stores]);
    }

    /**
     * 编辑员工
     */
    public function edit(Request $request)
    {
        if ($request->method() === 'POST') {
            $data = $request->post();
            
            try {
                $updateData = [
                    'username' => $data['username'], // 添加登录账号
                    'name' => $data['name'],
                    'store_id' => $data['store_id'],
                    'role' => $data['role'],
                    'status' => $data['status'],
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                
                // 如果修改了密码
                if (!empty($data['password'])) {
                    $updateData['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                    
                    // 同步更新 wa_admins 表中的密码
                    Db::table('wa_admins')
                        ->where('id', $data['admin_id']) // 假设您在前端传递 admin_id
                        ->update(['password' => $updateData['password']]);
                }
                
                Db::table('ky_staff')
                    ->where('id', $data['id'])
                    ->update($updateData);
                
                return json(['code' => 0, 'msg' => '编辑成功']);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => '编辑失败：' . $e->getMessage()]);
            }
        }
        
        $id = $request->get('id');
        $staff = Db::table('ky_staff')->where('id', $id)->first();
        
        // 获取门店列表
        $stores = Db::table('ky_store')->where('status', 1)->get();
        
        return $this->view('admin/staff/edit', ['staff' => $staff, 'stores' => $stores]);
    }

    /**
     * 删除员工
     */
    public function delete(Request $request)
    {
        $id = $request->post('id');
        
        try {
            Db::table('ky_staff')->where('id', $id)->delete();
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 交班管理页面
     */
    public function shift()
    {
        return $this->view('admin/staff/shift');
    }

    /**
     * 获取当前班次统计
     */
    public function currentShift()
    {
        try {
            $staffId = session('staff_id');
            $shiftStartTime = session('shift_start_time');
            
            if (!$shiftStartTime) {
                return json(['code' => 1, 'msg' => '未开始交班']);
            }
            
            // 获取当前班次的订单统计
            $stats = Db::table('ky_order')
                ->where('staff_id', $staffId)
                ->where('created_at', '>=', $shiftStartTime)
                ->selectRaw('
                    SUM(CASE WHEN payment_method = 1 THEN amount ELSE 0 END) as cash_amount,
                    SUM(CASE WHEN payment_method = 2 THEN amount ELSE 0 END) as wechat_amount,
                    SUM(CASE WHEN payment_method = 3 THEN amount ELSE 0 END) as alipay_amount,
                    SUM(amount) as total_amount
                ')
                ->first();
                
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'cash_amount' => $stats->cash_amount ?? 0,
                    'wechat_amount' => $stats->wechat_amount ?? 0,
                    'alipay_amount' => $stats->alipay_amount ?? 0,
                    'total_amount' => $stats->total_amount ?? 0
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '获取统计失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取交班记录列表
     */
    public function shiftList(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 15);
        $staffId = $request->input('staff_id', '');
        $dateRange = $request->input('date_range', '');
        
        $query = Db::table('ky_staff_shift')
            ->leftJoin('ky_staff', 'ky_staff_shift.staff_id', '=', 'ky_staff.id')
            ->leftJoin('ky_store', 'ky_staff_shift.store_id', '=', 'ky_store.id')
            ->select(
                'ky_staff_shift.*',
                'ky_staff.name as staff_name',
                'ky_store.name as store_name'
            );
            
        if ($staffId) {
            $query->where('ky_staff_shift.staff_id', $staffId);
        }
        
        if ($dateRange) {
            $dates = explode(' - ', $dateRange);
            if (count($dates) == 2) {
                $query->whereBetween('ky_staff_shift.created_at', [
                    $dates[0] . ' 00:00:00',
                    $dates[1] . ' 23:59:59'
                ]);
            }
        }
        
        $total = $query->count();
        $shifts = $query->offset(($page - 1) * $limit)
                       ->limit($limit)
                       ->orderBy('ky_staff_shift.id', 'desc')
                       ->get();
                       
        return json([
            'code' => 0,
            'msg' => 'success',
            'count' => $total,
            'data' => $shifts
        ]);
    }

    /**
     * 结束交班
     */
    public function endShift(Request $request)
    {
        try {
            $staffId = session('staff_id');
            $storeId = session('store_id');
            $shiftStartTime = session('shift_start_time');
            
            if (!$shiftStartTime) {
                return json(['code' => 1, 'msg' => '未开始交班']);
            }
            
            // 获取当前班次的订单统计
            $stats = Db::table('ky_order')
                ->where('staff_id', $staffId)
                ->where('created_at', '>=', $shiftStartTime)
                ->selectRaw('
                    SUM(CASE WHEN payment_method = 1 THEN amount ELSE 0 END) as cash_amount,
                    SUM(CASE WHEN payment_method = 2 THEN amount ELSE 0 END) as wechat_amount,
                    SUM(CASE WHEN payment_method = 3 THEN amount ELSE 0 END) as alipay_amount,
                    SUM(amount) as total_amount
                ')
                ->first();
                
            // 创建交班记录
            Db::table('ky_staff_shift')->insert([
                'staff_id' => $staffId,
                'store_id' => $storeId,
                'start_time' => $shiftStartTime,
                'end_time' => date('Y-m-d H:i:s'),
                'cash_amount' => $stats->cash_amount ?? 0,
                'wechat_amount' => $stats->wechat_amount ?? 0,
                'alipay_amount' => $stats->alipay_amount ?? 0,
                'total_amount' => $stats->total_amount ?? 0,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            // 清除session中的班次开始时间
            session(['shift_start_time' => null]);
            
            return json(['code' => 0, 'msg' => '交班成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '交班失败：' . $e->getMessage()]);
        }
    }

    /**
     * 交班详情
     */
    public function shiftDetail(Request $request)
    {
        $id = $request->get('id');
        
        try {
            $shift = Db::table('ky_staff_shift')
                ->leftJoin('ky_staff', 'ky_staff_shift.staff_id', '=', 'ky_staff.id')
                ->leftJoin('ky_store', 'ky_staff_shift.store_id', '=', 'ky_store.id')
                ->where('ky_staff_shift.id', $id)
                ->select(
                    'ky_staff_shift.*',
                    'ky_staff.name as staff_name',
                    'ky_store.name as store_name'
                )
                ->first();
                
            if (!$shift) {
                return json(['code' => 1, 'msg' => '交班记录不存在']);
            }
            
            // 获取订单列表
            $orders = Db::table('ky_order')
                ->where('staff_id', $shift->staff_id)
                ->whereBetween('created_at', [$shift->start_time, $shift->end_time])
                ->get();
                
            $shift->orders = $orders;
            
            return json(['code' => 0, 'msg' => 'success', 'data' => $shift]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '获取详情失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除交班记录
     */
    public function deleteShift(Request $request)
    {
        $id = $request->post('id');
        
        try {
            Db::table('ky_staff_shift')->where('id', $id)->delete();
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取员工列表
     */
    public function getList(Request $request)
    {
        try {
            $staff = Db::table('ky_staff')
                ->where('status', 1)  // 只获取在职员工
                ->select('id', 'name')  // 只需要id和名称
                ->orderBy('id', 'asc')
                ->get();
                
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $staff
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '获取员工列表失败：' . $e->getMessage(),
                'data' => []
            ]);
        }
    }
} 